package
{
	import flash.display.Sprite;
	import flash.filesystem.File;
	import flash.filesystem.FileMode;
	import flash.filesystem.FileStream;
	import flash.utils.ByteArray;
	
	public class OceanEditor extends Sprite
	{
		public var colorNone:int = 0xFFbdbdbd;
		public var colors:Array = [ 0xFF56f5d8, 0xFF00ecad, 0xFF75f038,
			0xFFcfff00, 0xFFffff00, 0xFFffea50, 0xFFffcd50, 0xFFffa250,
			0xFFff7f50, 0xFFff6347, 0xFFff0000 ];
		public var scales:Array = [3, 4, 5, 6, 7, 8, 9, 10, 11, 12, int.MAX_VALUE];
		public var cellWidth:int = 229;
		public var cellHeight:int = 169;
		
		public function OceanEditor()
		{
			var file:File = new File("D:/work/java/BitmapTest/sample.txt");
			var stream:FileStream = new FileStream();
			stream.open(file, FileMode.READ);
			var line:String = readLine(stream);
			var lineNum:int = 0;
			var rowNum:int = 0;
			var cellNum:int = 0;
			var cell:ByteArray = new ByteArray();
			var total:ByteArray = new ByteArray();
			while (line != null) {
//				trace("line"+lineNum+":" + line);
				if (line.length > 100) {
					parse(line, cell);
					lineNum++;
					rowNum++;
					if (rowNum == cellHeight) {
						cell.compress();
						total.writeInt(cell.length);
						total.writeBytes(cell);
						cell = new ByteArray();
						//					buildImage(cellNum + ".png", cellData);
						cellNum++;
						trace(cellNum);
						rowNum = 0;
					}
				}
				line = readLine(stream);
				//			trace(line);
			}
			stream.close();
			var out:File = new File("D:/work/flash/Ocean/data");
			var outStream:FileStream = new FileStream();
			outStream.open(out, FileMode.WRITE);
			outStream.writeBytes(total);
			outStream.close();
		}
			
		public function readLine(stream:FileStream):String {
			if (stream.bytesAvailable == 0) return null;
			var buf:ByteArray = new ByteArray();
			var b:int = stream.readByte();
			while (b != 13) {
				buf.writeByte(b);
				if (stream.bytesAvailable > 0) {
					b = stream.readByte();
				} else {
					break;
				}
			}
			if (stream.bytesAvailable >= 0)
				stream.readByte();
			buf.position = 0;
			return buf.readMultiByte(buf.length, "UTF-8");
		}
		
		public function parse(line:String, out:ByteArray):void {
			var c:String;
			var wi:int = 0;
			var buf:String = "";
			var z:Number;
			var old:int = out.length;
			for (var i:int = 0; i < line.length; i++) {
				c = line.charAt(i);
				if (c == ' ') {
					if (buf.length == 0) {
						continue;
					} else {
						z = Number(buf);
						out.writeFloat(z);
						wi++;
						buf = "";
					}
				} else {
					buf += c;
				}
				
			}
			if (buf.length > 0) {
				z = Number(buf);
				out.writeFloat(z);
			}
//			trace("write bytes count:" + (out.length-old));
		}
	}
}